<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>

      </div>

      <!-- 放置table组件 -->
      <el-table :data="list" border>
        <!-- 放置列 -->
        <el-table-column type="index" :index="index" align="center" width="80" label="序号" />
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else> {{ row.name }} </span>
          </template>
        </el-table-column>

        <el-table-column prop="state" align="center" width="150" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
          <!-- <template #default="obj">
            {{ obj.row.state ? '已启用' : '未启用' }}
          </template> -->
        </el-table-column>

        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click=" updateRole(row)">确定</el-button>
              <el-button size="mini" @click="onCancelEditRow(row)">取消</el-button>
            </template>

            <template v-else>
              <!-- 非编辑状态 -->
              <el-button type="text" @click="onAssign(row.id)">分配权限</el-button>
              <el-button type="text" @click="onEditRow(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="onDeleteRole(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>

      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="center">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>

    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="onCancel">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>

        <el-form-item label="启用">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>

        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>

        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="addRole">确定</el-button>

              <el-button size="mini" @click="onCancel">取消</el-button>

            </el-col>

          </el-row>

        </el-form-item>

      </el-form>

    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
      <!-- expand-on-click-node 关闭点击折叠节点 -->
      <!--  show-checkbox 开启复选框 -->
      <!-- default-checked-keys 设置默认选中的节点 -->
      <!-- node-key 告诉树, id字段是唯一的 -->
      <!-- check-strictly:  关闭父子联动 -->
      <!-- $refs.xxx.getCheckedKeys() 可以获取用户选中的节点 -->
      <el-tree
        ref="treeRef"
        node-key="id"
        :default-checked-keys="permIds"
        :check-strictly="true"
        show-checkbox
        :data="permissionData"
        default-expand-all
        :props="{ label: 'name' }"
        :expand-on-click-node="false"
      />
      <el-row :style="{ paddingTop: '20px' }" type="flex" justify="center">
        <el-button size="mini" type="primary" @click="assignPermission">确定</el-button>
        <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>

</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { getRoleListAPI, addRoleAPI, updateRoleAPI, deleteRoleAPI, getRoleDetailAPI, assignPermAPI } from '@/api/role'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      index: 1,
      showDialog: false,
      roleForm: {
        name: '',
        state: 0, // 0 未启用 1 已启用
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: [],
      permList: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleListAPI(this.pageParams)
      console.log('获取角色数据  ----->  ', res)
      this.list = res.rows // 赋值数据
      this.list.forEach(item => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题  数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = res.total // 总条数
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
      this.index = this.pageParams.pagesize * (this.pageParams.page - 1) + 1
    },
    async addRole() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRoleAPI(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.onCancel()
          // this.pageParams.page = this.pageParams.total + 1
          // this.changePage(this.pageParams.total)
        }
      })
    },
    onCancel() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
    },
    onEditRow(row) {
      row.isEdit = true
      // 保存编辑前的数据
      row.editRow = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    onCancelEditRow(row) {
      row.isEdit = false
      row.editRow = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    async updateRole(row) {
      if (row.editRow.name && row.editRow.description) {
        // 下一步操作
        await updateRoleAPI({ ...row.editRow, id: row.id })
        // 更新成功
        this.$message.success('更新角色成功')
        // 更新显示数据  退出编辑状态
        // row.name = row.editRow.name // eslint的一校验 误判
        // Object.assign(target, source)
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        }) // 规避eslint的误判
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async onDeleteRole(id) {
      await deleteRoleAPI(id)
      this.getRoleList()
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.$message.success('删除角色成功')
    },
    async onAssign(id) {
      const res = await getPermissionListAPI()
      this.permissionData = transListToTreeData(res, 0)
      this.currentRoleId = id
      this.permIds = (await getRoleDetailAPI(id)).permIds
      console.log('this.permIds  ----->  ', this.permIds)
      this.showPermissionDialog = true
    },
    async assignPermission() {
      await assignPermAPI({
        id: this.currentRoleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
  .role-operate {
  padding: 10px;
}
</style>
